
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions


# 使用jwt自定认证类
# from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework_jwt.utils import jwt_decode_handler


class MyToken(BaseJSONWebTokenAuthentication):

    def authenticate(self, request):
        # 获取token
        jwt_value = str(request.META.get('HTTP_AUTHORIZATION'))
        # 认证 token对不对
        try:
            payload = jwt_decode_handler(jwt_value)
            print(payload)
            print(type(payload))
        # except jwt.ExpiredSignature:
        #     msg = _('Signature has expired.')
        #     raise exceptions.AuthenticationFailed(msg)
        # except jwt.DecodeError:
        #     msg = _('Error decoding signature.')
        #     raise exceptions.AuthenticationFailed(msg)
        # except jwt.InvalidTokenError:
        except Exception as e:
            print(e)
            raise exceptions.AuthenticationFailed('认证失败')

        user = self.authenticate_credentials(payload)
        return user, None